#!/bin/sh /etc/rc.common

START=09

boot() {
	local kmod
	local enable="$( uci -q get kmods.kmods.enable )"
	if echo "$enable" | grep -qFw "i915-sriov" || is_white_list; then
		local FAILFILE=/etc/config/.i915_sriov_boot
		local count=$(cat $FAILFILE)
		[[ -n "$count" ]] || count=0
		[[ $count -le 2 ]] || return 0
		count=$(( $count + 1 ))
		echo "$count" > $FAILFILE
		sync $FAILFILE
		[[ $count -le 2 ]] || return 0

		local release="$(uname -r)"
		[[ -n "$release" ]] || return 0

		echo "enable i915-sriov" >>/dev/kmsg
		ls /lib/modules/$release/i915-sriov/ 2>/dev/null | while read kmod; do
			if [[ "$kmod" = "*.ko" ]]; then
				[[ -f /lib/modules/$release/$kmod ]] || continue
				mount --bind /lib/modules/$release/i915-sriov/$kmod /lib/modules/$release/$kmod
			else
				if [[ -f /etc/modules.d/$kmod ]]; then
					mount --bind /lib/modules/$release/i915-sriov/$kmod /etc/modules.d/$kmod
				else
					local target=$(ls /etc/modules.d/ 2>/dev/null | grep "^[0-9_-]*-$kmod\$" | head -1)
					[[ -n "$target" ]] || continue
					mount --bind /lib/modules/$release/i915-sriov/$kmod /etc/modules.d/$target
				fi
			fi
		done
	fi
}

is_white_list() {
	grep -qFw 0x8086 /sys/devices/pci0000:00/0000:00:02.0/vendor || return 1
	[[ "$(($(cat /sys/devices/pci0000:00/0000:00:02.0/class) & 0xff0000 ^ 0x030000))" = "0" ]] || return 1
	white_list | grep -v '^#' | tr '[A-Z]' '[a-z]' | sed 's/^\</0x/' | \
		grep -qFf /sys/devices/pci0000:00/0000:00:02.0/device || return 1
	echo "$(cat /sys/devices/pci0000:00/0000:00:02.0/device) is in i915-sriov white list" >>/dev/kmsg
	return 0
}

white_list() {
	echo '
# ADL-S
4680
4682
4688
468A
468B
4690
4692
4693
# ADL-P
46A0
46A1
46A2
46A3
46A6
46A8
46AA
462A
4626
4628
46B0
46B1
46B2
46B3
46C0
46C1
46C2
46C3
# ADL-N
46D0
46D1
46D2
46D3
46D4
# RPL-S
A780
A781
A782
A783
A788
A789
A78A
A78B
# RPL-U
A721
A7A1
A7A9
# RPL-P
A720
A7A0
A7A8
'
}
